const { src, dest, series, parallel, watch } = require('gulp')

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()

const del = require('del')
const browserSync = require('browser-sync')
const bs = browserSync.create()

const stylelint = require('stylelint');
const scss = require('postcss-scss');
const reporter = require('postcss-reporter');
const minimist = require('minimist');
const args = minimist(process.argv.slice(2));

const isProd = process.env.NODE_ENV ? process.env.NODE_ENV === 'production' : args.production || args.prod || false

const data = {
  menus: [{
    name: 'Home',
    icon: 'aperture',
    link: 'index.html'
  },
  {
    name: 'Features',
    link: 'features.html'
  },
  {
    name: 'About',
    link: 'about.html'
  },
  {
    name: 'Contact',
    link: '#',
    children: [
      {
        name: 'Twitter',
        link: 'https://twitter.com/w_zce'
      },
      {
        name: 'About',
        link: 'https://weibo.com/zceme'
      },
      {
        name: 'divider'
      },
      {
        name: 'About',
        link: 'https://github.com/zce'
      }
    ]
  }],
  pkg: require('./package.json'),
  date: new Date()
}

const clean = () => {
  return del(['dist', 'temp'])
}

const style = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const page = () => {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({
      defaults: {
        cache: false,
        locals: data
      }
    }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}

const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  // watch('src/assets/images/**', image)
  // watch('src/assets/fonts/**', font)
  // watch('public/**', extra)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2000,
    // files: 'dist/**',
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))
}

const compile = parallel(style, script, page)

const styleLint = () => {
  return src('assets/styles/*.scss', { base: 'src', cwd: 'src'})
    .pipe(plugins.postcss([
      stylelint({ fix: args.fix }),
      reporter()
    ], { syntax: scss }))
}

const scriptsLint = () => {
  return src('assets/scripts/*.js', { base: 'src', cwd: 'src'})
    .pipe(plugins.eslint({ fix: args.fix }))
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError())
}

// eslint
const lint = parallel(styleLint, scriptsLint)

// 打包
const build = series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

// 开发阶段
const dev = series(compile, serve)

const prodServe = () => {
  bs.init({
    notify: false,
    port: 2000,
    server: {
      baseDir: 'dist'
    }
  })
}

const start = series(build, prodServe)

module.exports = {
  lint,
  build,
  dev,
  clean,
  serve,
  start,
  deploy: build
}